<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/18 19:47
 * Modified Time: 2019/7/18 19:47
 * Version: 2.0
 */

namespace App\Modules\MemberCard\Repositores;


use App\Models\MemberCardFlow;
use App\Modules\MemberCard\Criterias\GetCenterCardFlowListCriteria;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;

class MemberCardFlowRepository extends BaseRepository
{
    public function model()
    {
        return MemberCardFlow::class;
    }

    /**
     * 获取今日会员卡销售金额
     * @param $storeId
     * @param int $userId
     * @return mixed
     */
    public function getMemberCardSaleAmount($storeId, $userId = 0,$dateList=null)
    {
        $where = empty($userId) ? ['store_id' => $storeId] : [
            'store_id' => $storeId,
            'user_id' => $userId
        ];

        $model = $this->model
	        ->where($where)
	        ->whereIn('type', [config('constant.memberCard.type.handle'), config('constant.memberCard.type.recharge')]);

	    isset($dateList) ?
		    $model->whereDate('created_at','<=',$dateList['start_date'])
			    ->whereDate('created_at','>=',$dateList['end_date'])
		    :
		    $model->whereDate('created_at',date('Y-m-d'));
	    return $model->sum('real_amount');
    }


	/**
	 * 会员服务消费统计
	 * @param $storeId
	 * @param $dateList
	 * @return mixed
	 */
    public function consumptionAmountsByStoreAndDate($storeId,$dateList){
	    $model = $this->model
		    ->where(['store_id'=>$storeId,'type'=>config('constant.memberCard.type.consume')]);
	    $model =  !empty($dateList) ?
		    $model->whereDate('created_at','<=',$dateList['start_date'])
			    ->whereDate('created_at','>=',$dateList['end_date'])
		    :
		    $model->whereDate('created_at',date('Y-m-d'));
	    return $model->sum('balance');
    }

	/**
	 * 计算店铺或者理发的会员卡单数
	 * @param $storeId
	 * @param $userId
	 * @return mixed
	 */
	public function getMemberCardSaleCount($storeId,$userId){
		$where = empty($userId) ? ['store_id' => $storeId] : [
			'store_id' => $storeId,
			'user_id' => $userId
		];
		return  $this->model->where($where)->whereIn('type', [config('constant.memberCard.type.handle'), config('constant.memberCard.type.recharge')])->whereDate('created_at', date('Y-m-d'))->count();
	}


    /*
     * 开卡
     */
    public function init($member_card_id, $member_id, $store_id, $category, $user_id, $count, $balance, $real_amount, $payment)
    {
        $data = [
            'card_id' => $member_card_id,
            'member_id' => $member_id,
            'store_id' => $store_id,
            'type' => 1,
            'card_type' => $category,
            'user_id' => $user_id,
            'real_amount' => $real_amount,
            'payment' => $payment,
            'count' => $count,
            'balance' => $balance
        ];

        return $this->updateOrCreate($data);
    }

    /*
     * 消费
     */
    public function consumption($member_card_id, $member_id, $store_id, $category, $user_id, $amount, $real_amount = 0)
    {
        $data = [
            'card_id' => $member_card_id,
            'member_id' => $member_id,
            'store_id' => $store_id,
            'type' => 3,
            'card_type' => $category,
            'user_id' => $user_id,
            'real_amount' => $real_amount
        ];

        if ($category == 1) {
            $data['count'] = $amount;
        } else {
            $data['balance'] = $amount;
        }

        return $this->updateOrCreate($data);
    }

    /**
     * 充值
     * @param $member_card_id
     * @param $member_id
     * @param $store_id
     * @param $category
     * @param $user_id
     * @param $amount
     * @param int $real_amount
     * @return mixed
     */
    public function recharge($member_card_id, $member_id, $store_id, $category, $user_id, $count, $balance, $real_amount = 0, $payment)
    {
        $data = [
            'card_id' => $member_card_id,
            'member_id' => $member_id,
            'store_id' => $store_id,
            'type' => 2,
            'card_type' => $category,
            'user_id' => $user_id,
            'real_amount' => $real_amount,
            'count' => $count,
            'balance' => $balance,
            'payment' => $payment,
        ];

        return $this->create($data);
    }

    public function transfer($member_card_id, $store_id, $category, $user_id, $count,$balance)
    {
        $data = [
            'card_id' => $member_card_id,
            'member_id' => '',
            'store_id' => $store_id,
            'type' => 4,
            'card_type' => $category,
            'user_id' => $user_id,
            'real_amount' => 0,
            'payment' => null,
        ];

        if ($category == 1) {
            $data['count'] = $count;
            $data['balance'] = $balance;
        } else {
            $data['balance'] = $balance;
        }

        return $this->updateOrCreate($data);
    }

    /**
     * 新增卡流水
     * @param $cardType
     * @param $cardId
     * @param $memberId
     * @param $barberId
     * @param $storeId
     * @param $orderId
     * @param int $type
     * @param int $count
     * @param int $balance
     * @param int $real_amount
     * @return mixed
     */
    public function addFlowMemberCard($cardType, $cardId, $memberId, $barberId, $storeId, $type = 3, $orderId = 0, $count = 0,$balance=0, $real_amount = 0)
    {
        $data = [
            'card_id' => $cardId,
            'member_id' => $memberId,
            'store_id' => $storeId,
            'user_id' => $barberId,
            'type' => $type,
            'card_type' => $cardType,
            'count' => $cardType == 1 ? $count : 0,
            'balance' => $balance,
            'real_amount' => ($type == 1 || $type == 2) && !empty($real_amount) ? $real_amount : 0,
            'order_id' => (($type == 3) && !empty($orderId)) ? $orderId : 0
        ];
        return $this->create($data);
    }

    /**
     * 查询某天的店铺开卡情况
     * @param $date
     * @return mixed
     */
    public function getStoreCardAmount($date)
    {
        $cardAmountList = $this->model->selectRaw('store_id,sum(real_amount) as amount,sum(id),count')->groupBy('store_id')->whereDate('created_at', $date)->get()->toArray();

        return empty($cardAmountList) ? [] : array_column($cardAmountList, null, 'store_id');
    }


    /**
     * 计算理发师充值办卡的贡献值
     * @param $storeId
     * @param $startDate
     * @param $endDate
     * @return mixed
     * @author Happy dong
     * @modifiedTime 2019-08-20 20:06
     */
    public function getAmountRankListByBarberId($storeId, $startDate, $endDate)
    {
        return $this->model
            ->selectRaw('sum(hx_member_card_flow.real_amount - hx_royalty.amount) as counts,hx_member_card_flow.user_id')
            ->with(['user' => function ($v) {
                $v->select(['id', 'nick', 'portrait'])->with('picture:id,image');
            }])
             ->leftJoin('royalty',function($v){
                 $v->on('royalty.item_id','=','member_card_flow.id')->where('royalty.type',2);
             })
            ->whereRaw('hx_member_card_flow.store_id ="' . $storeId . '" and date(hx_member_card_flow.created_at) <= "' . $startDate . '" and date(hx_member_card_flow.created_at) >="' . $endDate . '"   and hx_member_card_flow.type !=3 group by hx_member_card_flow.user_id order by counts desc')
            ->get();
    }


    /**
     * 店铺开卡订单流水
     * @param $storeId
     * @param $startDate
     * @param $endDate
     * @param bool $isList
     * @param null $pageSize
     * @return mixed
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     * @author Happy dong
     * @modifiedTime 2019-08-20 19:39
     */
    public function getFlowList($storeId, $startDate, $endDate, $isList = false, $pageSize = null, $user_id = null)
    {
        $pageSize = empty($pageSize) ? 10 : $pageSize;
        $result = $this->pushCriteria(new GetCenterCardFlowListCriteria($storeId, $startDate, $endDate, $isList, $user_id));

        if ($isList) {
            $list = $result->get();
        } else {
            $list = $result->paginate($pageSize, ['*'], 'paginate');
        }
        foreach ($list as $v){
        	if($v->type == 4){
        		$v->card->name =  $v->card->name .'(老会员导入)';
	        }
        }
        return $list;
    }

    /*
     * 某张会员卡充值总额及余额统计
     */
    public function getRechargeFlowSum($member_card_id, $attribute)
    {
        if ($attribute == 1) {
            return $this->model
                ->where(function ($query) {
                    $query->where('type', 2)->orWhere('type', 1);
                })
                ->where('card_id', $member_card_id)
                ->sum('real_amount');
        } else {
            return $this->model
                ->where(function ($query) {
                    $query->where('type', 2)->orWhere('type', 1);
                })
                ->where('card_id', $member_card_id)
                ->sum('balance');
        }

    }

    /**
     * 获取今日会员卡销售金额
     * @param $storeId
     * @param int $userId
     * @return mixed
     */
    public function getMemberCardSaleAmountDate($user_id, $store_id, $end_day)
    {
        $end_day = strtotime($end_day);
        return $this->model->where('user_id', $user_id)
            ->whereDate('created_at', '>=', $end_day)
            ->where('store_id', $store_id)
            ->get()
            ->sum('real_price');
    }


    public function getCardSalesList($dateList,$storeId,$pageSize){
        return $this->model
	        ->with(['royalty'=>function($v){
        	$v->select(['id','amount'])->where(['type'=>2]);
        },'member:id,name,face','card:id,name'])
	        ->where('store_id','=',$storeId)
	        ->whereIn('type',[1,2])
	        ->whereDate('created_at','>=',$dateList['end_date'])
	        ->whereDate('created_at','<=',$dateList['start_date'])
	        ->paginate($pageSize, ['*'], 'paginate');
    }

	/**
	 * 会员卡利润
	 * @param $dateList
	 * @param $storeId
	 * @param $userId
	 * @return float
	 */
    public function getCardProfit($dateList,$storeId,$userId){
	    $sql = 'select sum(`hx_member_card_flow`.`real_amount`) as amount, sum(`hx_royalty`.`amount`)  as cost  from `hx_member_card_flow` left join `hx_royalty` on `hx_royalty`.`item_id` = `hx_member_card_flow`.`id` and `hx_royalty`.`type` = 2
 where (`hx_member_card_flow`.`store_id` = '.$storeId.')   and
 date(`hx_member_card_flow`.`created_at`) >= "'.$dateList['end_date'].'"
 and  date(`hx_member_card_flow`.`created_at`) <= "'.$dateList['start_date'].'"  and `hx_member_card_flow`.`type`=1';
	    empty($userId) ? : $sql.' and `hx_member_card_flow`.`user_id`="'.$userId.'"';

	    $data = DB::selectOne($sql);
	    $amount = isset($data->amount) ? $data->amount : 0;
	    $cost = isset($data->cost) ? $data->cost : 0;
	    return round($amount - $cost, 2);
    }
}
